package basedto

import (
	"errors"
	"gitee.com/ichub/goconfig/common/base/baseiface"
	"gitee.com/ichub/goconfig/common/base/baseutils"
	"gitee.com/ichub/goconfig/common/base/baseutils/jsonutils"
	"github.com/huandu/go-clone"
	"github.com/jinzhu/copier"
	"github.com/sirupsen/logrus"
	"reflect"
)

type BaseProxy struct {
	Some any
}

func NewBaseProxy(some any) *BaseProxy {
	var proxy = new(BaseProxy)
	proxy.Some = some
	return proxy
}

func (this *BaseProxy) String() string {

	return jsonutils.ToJsonPretty(this.Some)
}

func (this *BaseProxy) ToString() string {

	return jsonutils.ToJsonPretty(this.Some)
}
func (this *BaseProxy) ToJsonBytes() []byte {

	var r, _ = jsonutils.ToJsonBytes(this.Some)
	return r
}

func (this *BaseProxy) Log() {
	var name = reflect.TypeOf(this.Some).String()
	logrus.Info(name, " =", this.String())

}
func (this *BaseProxy) Check() error {
	if this.Some == nil {
		return errors.New("some is nil!")
	}
	return nil

}

func (this *BaseProxy) Clone() any {

	return clone.Clone(this.Some)

}

func (this *BaseProxy) FromJson(body []byte) interface{} {
	jsonutils.FromJsonByte(body, this.Some)
	return this.Some

}
func (this *BaseProxy) ToJson() string {
	return jsonutils.ToJsonPretty(this.Some)

}

func (this *BaseProxy) ValueOf(another interface{}) {
	this.Some = another
}
func (this *BaseProxy) ToPrettyString() string {
	if this.Some == nil {
		return "{}"
	}
	return jsonutils.ToJsonPretty(this.Some)
}
func (this *BaseProxy) ContainsType(name string) bool {
	value := reflect.ValueOf(this.Some)
	if value.Kind() == reflect.Ptr {
		value = value.Elem()
	}

	if value.Kind() != reflect.Struct {
		return false
	}

	for i := 0; i < value.NumField(); i++ {
		logrus.Info(value.Field(i).Type().Name())
		if value.Field(i).Type().Name() == name {
			return true
		}
	}

	return false
}

func (this *BaseProxy) ValueFrom(from any) {
	//mapstructure.Decode(from, this.Some)
	var fromstr = jsonutils.ToJsonPretty(from)
	jsonutils.FromJson(fromstr, this.Some)

}

func (this *BaseProxy) CopyWithOption(from any) {
	copier.CopyWithOption(this.Some, from, copier.Option{IgnoreEmpty: true})

}
func (this *BaseProxy) Single() bool {
	return false

}
func (this *BaseProxy) Autoload() bool {
	return false

}
func (this *BaseProxy) AutoInject() bool {
	return false

}

func (this *BaseProxy) IfBaseEntity() bool {

	return baseutils.ContainsType(this.Some, "BaseEntity") ||
		baseutils.ContainsType(this.Some, "BaseEntitySingle") ||
		baseutils.ContainsTypeOfSub(this.Some, "BaseEntity") ||
		baseutils.ContainsTypeOfSub(this.Some, "BaseEntitySingle")

}
func (this *BaseProxy) Init() {
	this.Some.(baseiface.IpoolObj).Init()
}
func (this *BaseProxy) Shutdown() {
	this.Some.(baseiface.IpoolObj).Shutdown()
}
